package org.ISCS.service.utilimpl;

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Deployment;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.util.Config;
import io.kubernetes.client.util.Yaml;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;

@org.springframework.stereotype.Service
public class KubernetesService {
//    private final KubernetesClient client = new DefaultKubernetesClient();

    /*public void applyKubernetesYaml(String yamlPath) {
        System.out.println("Applying Kubernetes YAML from " + yamlPath);

        try {
            Resource resource = new FileSystemResource(yamlPath);
            if (!resource.exists()) {
                System.out.println("YAML file does not exist at " + yamlPath);
                return;
            }

            try (InputStream is = resource.getInputStream()) {
                List<HasMetadata> entities = client.load(is).get();
                System.out.println("Loaded " + entities.size() + " entities from YAML");

                entities.forEach(entity -> {
                    if (entity == null) {
                        System.err.println("Entity is null");
                        return;
                    }
                    String kind = entity.getKind();
                    String name = entity.getMetadata().getName();
                    String namespace = entity.getMetadata().getNamespace();

                    System.out.println("Processing entity: Kind=" + kind + ", Name=" + name + ", Namespace=" + namespace);

                    if (entity instanceof Pod) {
                        Pod pod = (Pod) entity;
                        Pod createdPod = client.pods().inNamespace(namespace).createOrReplace(pod);
                        System.out.println("Created or replaced Pod: " + createdPod.getMetadata().getName() + " in namespace " + namespace);
                    } else if (entity instanceof Deployment) {
                        Deployment deployment = (Deployment) entity;
                        Deployment createdDeployment = client.apps().deployments().inNamespace(namespace).createOrReplace(deployment);
                        System.out.println("Created or replaced Deployment: " + createdDeployment.getMetadata().getName() + " in namespace " + namespace);
                    } else if (entity instanceof Service) {
                        Service service = (Service) entity;
                        Service createdService = client.services().inNamespace(namespace).createOrReplace(service);
                        System.out.println("Created or replaced Service: " + createdService.getMetadata().getName() + " in namespace " + namespace);
                    }
                });
            }

            System.out.println("Successfully applied Kubernetes YAML from " + yamlPath);
        } catch (IOException e) {
            System.err.println("Failed to apply Kubernetes YAML from " + yamlPath);
            e.printStackTrace();
        }
    }
*/

    public void applyKubernetesYaml(String yamlPath) {
        try (InputStream is = new FileInputStream(yamlPath);
             Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
            ApiClient client = Config.defaultClient();
            Configuration.setDefaultApiClient(client);

            // Use `Yaml.loadAll` to handle multi-document YAML
            for (Object obj : Yaml.loadAll(reader)) {
                if (obj instanceof V1Deployment) {
                    AppsV1Api api = new AppsV1Api(client);
                    V1Deployment deployment = (V1Deployment) obj;
                    V1Deployment createdDeployment = api.createNamespacedDeployment(
                            deployment.getMetadata().getNamespace(),
                            deployment,
                            null,
                            null, null);
                    System.out.println("Created or updated deployment: " +
                            createdDeployment.getMetadata().getName());
                } else if (obj instanceof V1Service) {
                    CoreV1Api api = new CoreV1Api(client);
                    V1Service service = (V1Service) obj;
                    V1Service createdService = api.createNamespacedService(
                            service.getMetadata().getNamespace(),
                            service,
                            null,
                            null,
                            null);
                    System.out.println("Created or updated service: " +
                            createdService.getMetadata().getName());
                } else {
                    // Handle other types as needed
                    System.out.println("Unknown type: " + obj.getClass());
                }
            }
        } catch (IOException | ApiException e) {
            throw new RuntimeException("Failed to apply Kubernetes YAML", e);
        }
    }

/*    public K8sinfo checkStatus(String namespace, String podName, String deploymentName, String serviceName) {
        K8sinfo k8sInfo = new K8sinfo();
        Pod pod = client.pods().inNamespace(namespace).withName(podName).get();
        Deployment deployment = client.apps().deployments().inNamespace(namespace).withName(deploymentName).get();
        Service service = client.services().inNamespace(namespace).withName(serviceName).get();

        k8sInfo.setPodStatus(pod != null && pod.getStatus().getPhase().equals("Running") ? 1 : 2);
        k8sInfo.setDeployStatus(deployment != null && deployment.getStatus().getReplicas() > 0 ? 1 : 2);
        k8sInfo.setServiceStatus(service != null ? 1 : 2);
        return k8sInfo;
    }*/
}
